#!/bin/bash

set -e

source "$(
  cd "$(dirname "$0")" || exit 1
  pwd
)/../common.sh"

# 安装编译前必要应用
function install_development() {
  sudo yum install -y wget tar libatomic environment-modules
  source /etc/profile
}

# 下载毕晟编译器
function download_bisheng() {
  echo "# 毕昇编译器正在下载"
  wget -t 40 -c -P "$1" https://mirrors.huaweicloud.com/kunpeng/archive/compiler/bisheng_compiler/bisheng-compiler-2.1.0-aarch64-linux.tar.gz
  if [[ $? -eq 0 ]]; then
    echo -e "\033[1;32;1m# 毕昇编译器已经下载成功\033[0m"
  else
    echo -e "\033[31m# 毕昇编译器下载失败,请重新执行脚本\033[0m"
    exit 1
  fi
}

# 安装毕晟编译器
function install_bisheng() {
  echo "# 毕昇编译器正在安装"
  tar xf "$1"/bisheng-compiler-2.1.0-aarch64-linux.tar.gz -C "$1" && rm -rf "$1"/bisheng-compiler-2.1.0-aarch64-linux.tar.gz
  mkdir -p "$2"/bisheng-compiler-2.1.0 && cp -r "$1"/bisheng-compiler-2.1.0-aarch64-linux/* "$2"/bisheng-compiler-2.1.0/
  echo -e "\033[1;32;1m# 毕昇编译器已经安装完毕\033[0m"
}

# 创建modulefiles文件
function write_bisheng_module() {
  cat >"$1/bisheng-compiler-2.1.0/bisheng_modulefiles" <<EOF
#%Module1.0
conflict bisheng
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
  variable modfile
  set modfile_path [file dirname \$modfile]
  return \$modfile_path
}
set pwd [getModulefileDir]
set BISHENG \$pwd
setenv BISHENG \$BISHENG
prepend-path PATH \$BISHENG/bin
prepend-path LD_LIBRARY_PATH \$BISHENG/lib
EOF
}

function main() {
  # 打印当前运行脚本信息
  print_current_running_script_info "bisheng-compiler-2.1.0.sh"
  # 校验安装路径与构建路径是否一致
  is_equal_build_install_path "$1" "$2"
  install_development
  # 下载毕晟编译器
  download_bisheng "$1"
  # 安装毕晟编译器
  install_bisheng "$1" "$2"
  # 创建modulefiles文件
  write_bisheng_module "$2"
  # 删除构建文件夹
  rm -rf "$1"/bisheng-compiler-2.1.0-aarch64-linux
}

main "$@"
